package com.zj.study.controller;

import com.zj.study.entity.User;
import com.zj.study.pojo.FinalResultVO;
import com.zj.study.service.UserService;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 赵赳
 * @since 2021/10/27 17:56
 */
@RestController
@CrossOrigin
public class DemoController {


  private UserService userService;
  private StringRedisTemplate redisTemplate;

  @Autowired
  public void setUserService(UserService userService) {
    this.userService = userService;
  }

  @Autowired
  public void setRedisTemplate(StringRedisTemplate redisTemplate) {
    this.redisTemplate = redisTemplate;
  }

  /**
   * 第一种
   */
  @PostMapping("/a")
  public void testA() {
    User user = new User();
    userService.save(user);
    Long id = user.getId();
    redisTemplate.opsForValue().set("a", id + "", 20, TimeUnit.SECONDS);
    testB(id);
  }

  @PostMapping("/b")
  public void testB(Long id) {
    try {
      // to do
      int m = 10;
      int i = 10 / 0;
    } catch (Throwable throwable) {
      String a = redisTemplate.opsForValue().get("a");
      // 删除数据
      userService.removeById(Long.parseLong(a));
      throw new RuntimeException("操作失败");
    }
  }


  /**
   * 测试计数
   *
   * @return
   */
  @PostMapping("/test/countSize")
  public FinalResultVO<Integer> countSize() {
    return userService.countSize();
  }


  /**
   * 返回文件流
   *
   * @param path
   * @param response
   * @return
   */
  @RequestMapping(value = "/imgRes", method = RequestMethod.POST)
  @ResponseBody
  public HttpServletResponse getImageRes(String path, HttpServletResponse response) {
    try {
      String url = "C:\\Users\\18210\\Pictures\\images\\微信图片_20210817162602.jpg";
      File file = new File(url);
      InputStream fis = new BufferedInputStream(new FileInputStream(file));
      byte[] buffer = new byte[fis.available()];
      fis.read(buffer);
      fis.close();
      response.reset();
      // 设置response的Header
      response.addHeader("Access-Control-Allow-Origin", "*");
      //response.addHeader("Access-Control-Allow-Method", "*");
      response.addHeader("Access-Control-Allow-Headers", "Content-Type");
      response.addHeader("Access-Control-Max-Age", "3600");

      response.addHeader("Content-Length", "" + file.length());
      response.setContentType("application/octet-stream");

      OutputStream toClient = new BufferedOutputStream(response.getOutputStream(), 888888);
      toClient.write(buffer);
      toClient.flush();
      toClient.close();
    } catch (IOException ex) {
      ex.printStackTrace();
    }
    return response;
  }

  /**
   * 文件下载
   *
   * @param path     路径
   * @param response httpResponse
   * @return 文件
   */
  @GetMapping("/downloadFile")
  public HttpServletResponse download(String path, HttpServletResponse response) {
    try {
      // path是指欲下载的文件的路径。
      path = "C:\\Users\\18210\\Pictures\\images\\微信图片_20210817162602.jpg";
      File file = new File(path);
      // 取得文件名。
      String filename = file.getName();
      // 取得文件的后缀名。
      String ext = filename.substring(filename.lastIndexOf("."));
      LocalDateTime time = LocalDateTime.now();
      DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
      var datetime = dtf2.format(time);
      filename = datetime + ext;

      // 以流的形式下载文件。
      BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file));
      //byte[] buffer = new byte[fis.available()];

      //var read = fis.read(buffer);
      //fis.close();
      // 清空response
      response.reset();
      // 设置response的Header
      response.addHeader("Content-Disposition",
          "attachment;filename=" + filename);
      response.addHeader("Content-Length", "" + file.length());
      OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
      response.setContentType("application/x-msdownload");

      byte[] buffer = new byte[1024];
      // 计算当前实际下载了多少字节
      long k = 0;
      while (k < file.length()) {
        int j = fis.read(buffer, 0, 1024);
        k += j;
        outputStream.write(buffer, 0, j);
      }
      //outputStream.write(buffer);
      outputStream.flush();
      fis.close();
      outputStream.close();
    } catch (IOException ex) {
      ex.printStackTrace();
    }
    return response;
  }


}
